
goog.provide('gaillard.Model');

goog.require('gaillard.utils');
goog.require('gaillard.KVOObject');
goog.require('goog.net.XhrIo');

/**
 *
 * @constructor
 * @extends {goog.ui.Component}
 */
gaillard.Model = function () {
    gaillard.KVOObject.call(this);
	this.geocoder_ = new google.maps.Geocoder();
    
    goog.events.listen(this, gaillard.Model.Datatype.ADDRESS, this.addressChanged_, false, this);
};

gaillard.Model.Datatype = {
    OPEN_INSERT_RESTAURANT: 'open_insert_restaurant',
    ADDRESS: 'address',
    RESTAURANT_LIST: 'restaurant_list',
    SELECTED_RESTAURANT: 'selected_restaurant',
    FOCUSED_RESTAURANT: 'focus_restaurant'
};

goog.inherits(gaillard.Model, gaillard.KVOObject);
goog.addSingletonGetter(gaillard.Model);

(function () {

	gaillard.Model.prototype.searchAddress = function (req) {

        var self = this;
		this.geocoder_.geocode( 
			{ 'address': req }, 
			function(results, status) {
				if (status == google.maps.GeocoderStatus.OK) {
					var result = results[0];
					self.set(gaillard.Model.Datatype.ADDRESS, result);
				}
			}
		);
	};
    
	function callbackInsertRestaurant(response) {
		
		console.debug(response);
		alert('insert ok');
	}
		
	gaillard.Model.prototype.insertRestaurant = function (restaurant) {
        
           
        if (restaurant[0].length > 0 &&
            restaurant[1].length > 0 &&
            restaurant[4].length > 0) {
            
            var data = {
                'name':restaurant[0],
                'address':restaurant[1],
                // 'link': restaurant[2],
                // 'phone': restaurant[3],
                'description':restaurant[4],
                'lat': restaurant[5],
                'lon': restaurant[6]
            };
        
            goog.net.XhrIo.send(
                '/r/put',
                callbackInsertRestaurant, 
                'POST',
                gaillard.utils.encodePostDataToString(data));
            
                
        }
	};
	
	
	
	gaillard.Model.prototype.addressChanged_ = function() {
        var address = this.get(gaillard.Model.Datatype.ADDRESS);
		this.getRestaurant(address.geometry.location);
	};
	
	function callbackGetRestaurant(event) {
		var response = event.target.getResponseJson();
		if (response.status == "success") {
			gaillard.Model.getInstance().set(gaillard.Model.Datatype.RESTAURANT_LIST, response.results);
		}				
	};
	
	gaillard.Model.prototype.getRestaurant = function (location) {
		var url = '/r/get' + "?lat="+location.lat()+"&lng="+location.lng();
		goog.net.XhrIo.send(url, callbackGetRestaurant);
	};

})();
